package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.take_delivery.OrderRepository;
import cn.itcast.bos.dao.take_delivery.WorkBillRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private WorkBillRepository workBillRepository;
	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Override
	public void saveOrder(Order order) {
		// 设置订单编号
		order.setOrderNum(UUID.randomUUID().toString());
		// 设置下单时间
		order.setOrderTime(new Date());
		// 设置订单状态 1：未取件
		order.setStatus("1");
		// 设置寄件区域
		Area area = order.getSendArea();
		Area persistSendArea = areaRepository.findByProvinceAndCityAndDistrict(area.getProvince(), area.getCity(),
				area.getDistrict());
		order.setSendArea(persistSendArea);
		// 设置收件区域
		Area area1 = order.getSendArea();
		Area persistRecArea = areaRepository.findByProvinceAndCityAndDistrict(area1.getProvince(), area1.getCity(),
				area1.getDistrict());
		order.setRecArea(persistRecArea);

		// 基于CRM地址完全匹配快递员，自动分单
		// 根据订单的寄件人地址去customer表查询对应的定区fixedAreaId
		String fixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL
				+ "/services/customerService/findFixAreaIdByAddress/" + order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		if (StringUtils.isNotBlank(fixedAreaId)) {
			// 如果fixedAreaId存在，根据fixedAreaId查询定区
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			// 查询定区下的快递员
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if (iterator.hasNext()) {
				// 保存订单
				saveOrder(order, iterator);
				// 生成工单
				generateWorkBill(order);
				return;
			}
		}
		// 基于分区匹配快递员，自动分单
		// 如果通过寄件地址没有匹配到定区,就通过省市区信息匹配分区，在找到定区，在匹配到快递员
		Set<SubArea> subareas = persistSendArea.getSubareas();
		for (SubArea subArea : subareas) {
			if (order.getSendAddress().contains(subArea.getKeyWords())
					|| order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					// 保存订单
					saveOrder(order, iterator);
					// 生成工单
					generateWorkBill(order);
					return;
				}
			}
		}
		//人工调度
		order.setOrderType("2");
		orderRepository.save(order);
	}

	// 生成工单
	private void generateWorkBill(final Order order) {
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setOrder(order);
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		workBill.setCourier(order.getCourier());
		final String randomNumeric = RandomStringUtils.randomNumeric(6);
		workBill.setSmsNumber(randomNumeric);
		// 保存工单
		workBillRepository.save(workBill);
		// 发送短信给快递员
		jmsTemplate.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("msg", "短信序号：" + randomNumeric + ",取件地址：" + order.getSendAddress() + ",联系人:"
						+ order.getSendName() + ",手机:" + order.getSendMobile() + "，快递员捎话：" + order.getSendMobileMsg());
				return mapMessage;
			}
		});
		workBill.setPickstate("已通知");
	}

	// 保存订单
	private void saveOrder(Order order, Iterator<Courier> iterator) {
		Courier courier = iterator.next();
		// 关联快递员
		order.setCourier(courier);
		// 设置自动分单
		order.setOrderType("1");
		orderRepository.save(order);
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		
		return orderRepository.findByOrderNum(orderNum);
	}

}
